package com.mask.im.business.strategy.impl.sendcode;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.BooleanUtil;
import com.mask.im.business.common.exception.BusinessException;
import com.mask.im.business.service.RedisService;
import com.mask.im.business.strategy.SendCodeStrategy;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.Random;

@Service
public abstract class AbstractSendCode implements SendCodeStrategy {

	@Autowired
	private RedisService redisService;

	protected String getCode() {
		StringBuilder code = new StringBuilder();
		Random random = new Random();
		while (code.length() < 6) {
			int nextInt = random.nextInt(9);
			code.append(nextInt);
		}
		return code.toString();
	}

	protected void checkEmailAndCode(String email, String sendCodeKey) {
		//校验手机号格式
		if (!Validator.isEmail(email)) {
			throw new BusinessException("邮箱格式错误");
		}
		//判断验证码是否在有效期
		Boolean aBoolean = redisService.hasKey(sendCodeKey + email);
		if (BooleanUtil.isTrue(aBoolean)) {
			throw new BusinessException("验证码仍在有效期内");
		}
	}

	protected void checkPhoneAndCode(String phone, String sendCodeKey) {
		//校验手机号格式
		if (!Validator.isMobile(phone)) {
			throw new BusinessException("手机格式错误");
		}
		//判断验证码是否在有效期
		Boolean aBoolean = redisService.hasKey(sendCodeKey + phone);
		if (BooleanUtil.isTrue(aBoolean)) {
			throw new BusinessException("验证码仍在有效期内");
		}
	}
}
